"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress"
import { BookOpen, MessageSquare, FileText, PenTool, Loader2 } from "lucide-react"
import { useUser } from "@/lib/user-context"
import { useToast } from "@/components/ui/use-toast"
import { getUserProgress } from "@/lib/api-service"

export default function ProgressPage() {
  const [progress, setProgress] = useState<any>({})
  const [isLoading, setIsLoading] = useState(true)
  const router = useRouter()
  const { user } = useUser()
  const { toast } = useToast()

  // 加载进度数据
  useEffect(() => {
    const loadProgress = async () => {
      if (!user) return

      setIsLoading(true)
      try {
        const data = await getUserProgress(user.id)
        setProgress(data)
      } catch (error) {
        console.error("Error loading progress:", error)
        toast({
          title: "加载失败",
          description: "无法加载进度数据，请稍后再试",
          variant: "destructive",
        })
      } finally {
        setIsLoading(false)
      }
    }

    loadProgress()
  }, [user, toast])

  // 如果用户未登录，重定向到首页
  useEffect(() => {
    if (!user) {
      toast({
        title: "请先登录",
        description: "您需要登录后才能查看学习进度",
        variant: "destructive",
      })
      router.push("/")
    }
  }, [user, router, toast])

  // 计算总体完成率
  const calculateOverallProgress = () => {
    const sections = ["vocabularyGrammar", "dialogueCloze", "reading", "writing"]
    let completedSections = 0

    sections.forEach((section) => {
      if (progress[section]?.completed) {
        completedSections++
      }
    })

    return (completedSections / sections.length) * 100
  }

  if (!user) {
    return null
  }

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8 flex flex-col items-center justify-center min-h-[60vh]">
        <Loader2 className="h-8 w-8 animate-spin mb-4" />
        <p>正在加载进度数据...</p>
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-2xl font-bold mb-8">学习进度</h1>

      <Card className="mb-8">
        <CardHeader>
          <CardTitle>总体进度</CardTitle>
          <CardDescription>您的学习完成情况</CardDescription>
        </CardHeader>
        <CardContent>
          <Progress value={calculateOverallProgress()} className="h-2 mb-2" />
          <p className="text-sm text-muted-foreground">完成率: {Math.round(calculateOverallProgress())}%</p>
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center space-x-4 pb-2">
            <BookOpen className="h-5 w-5 text-primary" />
            <div>
              <CardTitle>词汇与语法</CardTitle>
              <CardDescription>词汇和语法练习进度</CardDescription>
            </div>
          </CardHeader>
          <CardContent>
            {progress.vocabularyGrammar ? (
              <>
                <div className="flex justify-between mb-2">
                  <span>
                    得分: {progress.vocabularyGrammar.score}/{progress.vocabularyGrammar.total}
                  </span>
                  <span>
                    正确率: {Math.round((progress.vocabularyGrammar.score / progress.vocabularyGrammar.total) * 100)}%
                  </span>
                </div>
                <Progress
                  value={(progress.vocabularyGrammar.score / progress.vocabularyGrammar.total) * 100}
                  className="h-2"
                />
              </>
            ) : (
              <p className="text-muted-foreground">尚未开始练习</p>
            )}
          </CardContent>
          <CardFooter>
            <Button variant="outline" className="w-full" onClick={() => router.push("/practice/vocabulary-grammar")}>
              {progress.vocabularyGrammar ? "继续练习" : "开始练习"}
            </Button>
          </CardFooter>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center space-x-4 pb-2">
            <MessageSquare className="h-5 w-5 text-primary" />
            <div>
              <CardTitle>情景对话与完形填空</CardTitle>
              <CardDescription>对话和完形填空练习进度</CardDescription>
            </div>
          </CardHeader>
          <CardContent>
            {progress.dialogueCloze ? (
              <>
                <div className="flex justify-between mb-2">
                  <span>
                    得分: {progress.dialogueCloze.score}/{progress.dialogueCloze.total}
                  </span>
                  <span>
                    正确率: {Math.round((progress.dialogueCloze.score / progress.dialogueCloze.total) * 100)}%
                  </span>
                </div>
                <Progress value={(progress.dialogueCloze.score / progress.dialogueCloze.total) * 100} className="h-2" />
              </>
            ) : (
              <p className="text-muted-foreground">尚未开始练习</p>
            )}
          </CardContent>
          <CardFooter>
            <Button variant="outline" className="w-full" onClick={() => router.push("/practice/dialogue-cloze")}>
              {progress.dialogueCloze ? "继续练习" : "开始练习"}
            </Button>
          </CardFooter>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center space-x-4 pb-2">
            <FileText className="h-5 w-5 text-primary" />
            <div>
              <CardTitle>阅读理解</CardTitle>
              <CardDescription>阅读理解练习进度</CardDescription>
            </div>
          </CardHeader>
          <CardContent>
            {progress.reading ? (
              <>
                <div className="flex justify-between mb-2">
                  <span>
                    得分: {progress.reading.score}/{progress.reading.total}
                  </span>
                  <span>正确率: {Math.round((progress.reading.score / progress.reading.total) * 100)}%</span>
                </div>
                <Progress value={(progress.reading.score / progress.reading.total) * 100} className="h-2" />
              </>
            ) : (
              <p className="text-muted-foreground">尚未开始练习</p>
            )}
          </CardContent>
          <CardFooter>
            <Button variant="outline" className="w-full" onClick={() => router.push("/practice/reading")}>
              {progress.reading ? "继续练习" : "开始练习"}
            </Button>
          </CardFooter>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center space-x-4 pb-2">
            <PenTool className="h-5 w-5 text-primary" />
            <div>
              <CardTitle>写作练习</CardTitle>
              <CardDescription>写作练习进度</CardDescription>
            </div>
          </CardHeader>
          <CardContent>
            {progress.writing ? (
              <>
                <div className="flex justify-between mb-2">
                  <span>
                    完成: {progress.writing.answeredCount}/{progress.writing.total}
                  </span>
                  <span>完成率: {Math.round((progress.writing.answeredCount / progress.writing.total) * 100)}%</span>
                </div>
                <Progress value={(progress.writing.answeredCount / progress.writing.total) * 100} className="h-2" />
              </>
            ) : (
              <p className="text-muted-foreground">尚未开始练习</p>
            )}
          </CardContent>
          <CardFooter>
            <Button variant="outline" className="w-full" onClick={() => router.push("/practice/writing")}>
              {progress.writing ? "继续练习" : "开始练习"}
            </Button>
          </CardFooter>
        </Card>
      </div>
    </div>
  )
}
